<template>
  <div class="login-container">
    <van-nav-bar left-arrow @click-left="$router.back()" title="校园超市">
      <template #right>
        <van-icon @click="$router.push('/index')" name="shop-o" size="20" color="red" />
      </template>
    </van-nav-bar>
    <h3 class="title">账号登录</h3>

    <van-form ref="loginForm" @submit="debounce(login)()">
      <van-field :maxlength="11"
        :rules="[{ required: true, message: '请输入手机号' }, { pattern: telPattern, message: '请输入合法的手机号' }]" v-model="phone"
        placeholder="请输入手机号" />
      <van-field :rules="[{ required: true, message: '请输入登录密码' }]" type="password" v-model="password"
        placeholder="请输入登录密码" />
      <van-button block round color="red">立即登录</van-button>
    </van-form>
  </div>
</template>
  
<script>
import { debounce } from '@/plugins/util';
import { mapActions } from 'vuex';
export default {
  data() {
    return {
      // 默认账号和密码
      phone: "18710950999",
      password: "123",
      telPattern: /^1[3456789]\d{9}$/
    }
  },
  methods: {
    ...mapActions('cart', ['getCartList']),
    debounce,
    login: function () {
      this.$refs.loginForm.validate().then(() => {
        this.$axios.post('/login', { phone: this.phone, password: this.password }).then(res => {
          this.$toast(res.msg);
          if (res.code == 200) {
            localStorage.setItem('userLoginInfo', JSON.stringify(res.list));
            // 请求购物车列表数据
            this.getCartList();
            // 自动跳转到用户之前操作的页面 或者 会员中心
            let url = this.$route.query.url ? this.$route.query.url : '/user';
            this.$router.push(url);
          }
        });
      }).catch(() => {
        console.log('表单校验失败');
      })

    }
  }
}
</script>
  
<style>
.login-container {
  padding: 10px;
}

.login-container h3 {
  font-size: 30px;
  color: #444;
  font-weight: normal;
  margin: 30px 0;
  text-align: center;

}

.login-container .van-cell {
  background: #f2f2f2;
  border-radius: 20px;
  margin: 20px 0;
}

.link {
  margin: 15px;
  font-size: 14px;
  display: block;
  color: #333;
  text-align: center;
}
</style>